package com.atguigu.yygh.order.api;


import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private PaymentService paymentService;


    // 生成微信二维码
    @GetMapping("createNative/{orderId}")
    public Result createNative(@PathVariable String orderId){

        // 微信返回很多数据,用map集合封装起来
        Map map = weixinService.createNative(orderId);
        return Result.ok(map);
    }

    //查询支付状态
        @GetMapping("queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable String orderId){

        // 根据订单id调用微信接口得到微信支付情况,实现支付状态查询
            Map<String,String> resultMap = weixinService.queryPayStatus(orderId);
            // 支付判断
        if(resultMap == null){
            return Result.fail().message("支付出错");
        }

        if("SUCCESS".equals(resultMap.get("trade_state"))){
            // 更新支付订单状态信息
            String out_trade_no = resultMap.get("out_trade_no");// 订单编号
            // 支付返回结果
            paymentService.paySuccess(out_trade_no,resultMap);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
        }
}
